<!-- home -->
<template>
  <div class="container">
    <van-nav-bar
      title="添加客户"
      class="navclass"
      left-arrow
      left-text="返回"
      @click-left="doback"
    />

    <van-cell title="填写人：" v-model="ywyname" />

    <van-field
      v-model="name"
      required
      label="客户名称："
      placeholder="请输入客户名称"
    />

    <van-cell  title="选择客户级别" required title-class="titleclass"   v-model="khjbname" center is-link @click="showKhjb" />
    <van-cell  title="选择客户状态" required title-class="titleclass"   v-model="khztname" center is-link @click="showKhzt" />

    <van-field
      v-model="telephone"
      required
      label="联系方式："
      placeholder="请输入客户手机号"
    />

    <van-field
      required
      readonly
      clickable
      name="area"
      :value="form.dlqy"
      label="所在地市"
      placeholder="点击选择省市区"
      @click="showArea = true"
    />

    <van-cell title="是否寄样品：">
      <van-radio-group v-model="sqypflag" direction="horizontal">
        <van-radio name="1">是</van-radio>
        <van-radio name="2">否</van-radio>
      </van-radio-group>
    </van-cell>

    <van-field
      v-model="address"
      required
      label="收货地址："
      placeholder="请输入收货地址"
      v-if="sqypflag == '1' "
    />

    <van-cell title="当前位置经度：" v-model="longitude" />
    <van-cell title="当前位置纬度：" v-model="latitude" />

    <div :style="{width:'100%',height:'200px',paddingTop:'20px'}">
      <el-amap vid="amap"  class="amap-demo" :center="center">
        <!-- 标记点 -->
        <el-amap-marker :position="center" vid="marker"></el-amap-marker>
        <!-- 圆 -->
        <el-amap-circle
          vid="circle"
          :center="center"
          :radius="radius"
          fill-opacity="0.2"
          strokeColor="#38f"
          strokeOpacity="0.8"
          strokeWeight="1"
          fillColor="#38f"
        ></el-amap-circle>
      </el-amap>
    </div>

    <div class="toolbar">
        <span v-if="loaded">
          location: lng = {{ longitude }} lat = {{ latitude }}
        </span>
      <span v-else>正在定位</span>
    </div>

    <van-popup v-model="showArea" position="bottom">
      <van-area
        :area-list="areaList"
        @cancel="showArea = false"
        @confirm="onConfirmArea"
      />
    </van-popup>

    <div  class="btn" >
      <van-button type="info" size="large" round @click="doSubmit" >提交</van-button>
    </div>

    <van-action-sheet v-model="jbShow" :actions="actions" @select="onSelectKhjb" />
    <van-action-sheet v-model="khztShow" :actions="khztActions" @select="onSelectKhzt" />

  </div>
</template>
<script src="http://res2.wx.qq.com/open/js/jweixin-1.6.0.js" type="text/javascript"></script>
<script>
import AreaList from '../../../static/area'
import { Dialog, Toast ,Grid,GridItem,Calendar,Cell} from 'vant'
import { addCost, queryUserInfo, updateCost,addCustomer,updateCustomer,getWxconfigInfo } from '../../api/api'
import AMap from 'vue-amap'
import wx from 'weixin-js-sdk'

export default {
  name:'addCustomer',
  data() {
    return {
      ywyname:'',
      showArea:false,
      areaList: AreaList,
      form: {},
      name:'',
      phone:'',
      jbShow:false,
      actions:[{id:'1',name:'A(重点客户)'},{id:'2',name:'B(普通客户)'},{id:'3',name:'C(非优先客户)'}],
      khztActions:[{id:'1',name:'初步接洽'},{id:'2',name:'持续跟进'},{id:'3',name:'达成成交'},{id:'4',name:'输单'}],
      khjb:'',
      khjbname:'请选择客户级别',
      //商家信息(包含坐标信息)
      businessDetail:{},
      //BMap类
      BMap: null,
      //地图对象
      map: null,
      radius:200,//圆半径，单位:米
      center: [113.753602,34.765515],
      lng: 0,
      lat: 0,
      loaded: false,
      plugin: [{
        enableHighAccuracy: true,//是否使用高精度定位，默认:true
        timeout: 100,          //超过10秒后停止定位，默认：无穷大
        maximumAge: 0,           //定位结果缓存0毫秒，默认：0
        convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
        showButton: true,        //显示定位按钮，默认：true
        buttonPosition: 'RB',    //定位按钮停靠位置，默认：'LB'，左下角
        showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
        showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
        panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
        zoomToAccuracy:true,//定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：f
        extensions:'all',
        pName: 'Geolocation',
        events: {
          init(o) {
            debugger
            // o 是高德地图定位插件实例
            o.getCurrentPosition((status, result) => {
              console.log(result)
              if (result && result.position) {
                self.lng = result.position.lng;
                self.lat = result.position.lat;
                self.center = [self.lng, self.lat];
                self.loaded = true;
                self.$nextTick();
              }
            });
          }
        }
      }],
      telephone:'',
      sqypflag:'2',
      address:'',
      khztname:'请选择',
      khzt:'',
      khztShow:false,
      latitude:'',//纬度
      longitude:'' //经度

    }
  },

  created() {
    this.queryUserInfo()
    this.ywyname = this.$store.getters.userName
    this.getWxconfigInfo()
  },
  mounted() {
    //这里的的参数除了debug和jsApiList，其他都是后端同事获取到后传给前端的
  },

  methods: {

    // 获取定位
    getLocation () {
      const _this = this
        var citySearch = new AMap.CitySearch()
        citySearch.getLocalCity(function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            // 查询成功，result即为当前所在城市信息
            console.log('通过ip获取当前城市：', result)
            _this.autolocation = result.city
          }
        })

    },

    getWxconfigInfo(){
      let that = this
      console.log(window.location.href)
      let param = {url:''}
      getWxconfigInfo(param).then(response =>{
        if (response.code === 200) {
          wx.config({
            debug: false, // 开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来，若要查看传入的参数，可以在 pc 端打开，参数信息会通过 log 打出，仅在 pc 端时才会打印。
            appId: response.data.appId, // 必填，公众号的唯一标识
            timestamp: response.data.timestamp, // 必填，生成签名的时间戳
            nonceStr: response.data.nonce_str, // 必填，生成签名的随机串
            signature: response.data.signature,// 必填，签名
            jsApiList: ['getLocation','checkJsApi', 'openLocation'] // 必填，需要使用的 JS 接口列表
          });

          wx.ready(function() {
            // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，
            wx.getLocation({
              type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
              success: function(res) {
                var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                var speed = res.speed; // 速度，以米/每秒计
                var accuracy = res.accuracy; // 位置精度
                console.log('longitude==>',longitude)
                console.log('latitude==>',latitude)
                that.latitude = latitude
                that.longitude = longitude
                that.center = [longitude,latitude]
                that.loaded = true
                var map = new AMap.Map('amap');
                var marker = new AMap.Marker({
                  position: new AMap.LngLat(longitude,latitude),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                  title: '客户位置'
                });
                map.add(marker);
              },
              fail: function(err) {
                alert("获取定位位置信息失败！")
              },
              cancel: function (res) {
                alert('用户拒绝授权获取地理位置');
              }
            });
          });

        } else {

        }
      })
    },

    onConfirmArea(values) {
      console.log(values)
      this.form.province = values[0].name
      this.form.city = values[1].name
      this.form.county = values[2].name

      const dlqy = values
        .filter((item) => !!item)
        .map((item) => item.name)
        .join('/')
      const qycode = values
        .filter((item) => !!item)
        .map((item) => item.code)
        .join('/')
      this.form.dlqy = dlqy
      this.form.qycode = qycode
      this.showArea = false
    },

    queryUserInfo(){
      let param = {}
      queryUserInfo(param).then(response =>{
        if (response.code === 200) {
          this.ywyname  = response.data.name
        } else {
          Toast.fail(response.msg)
        }
      })
    },

    doSubmit(){

      if(!this.name){
        Toast.fail('请填写客户名称')
        return
      }

      if(!this.telephone){
        Toast.fail('请填写联系方式')
        return
      }

      if(!this.khjb){
        Toast.fail('请选择客户级别')
        return
      }

      if(!this.khzt){
        Toast.fail('请选择客户状态')
        return
      }

      if(!this.form.qycode){
        Toast.fail('请选择客户所在地市')
        return
      }

      if(this.sqypflag == '1' && !this.address ){
        Toast.fail('请录入收货地址')
        return
      }

      let  param = {"khjb":this.khjb,name:this.name,telephone:this.telephone,area:this.form.dlqy,qycode:this.form.qycode ,ywyname:this.ywyname,sqypflag:this.sqypflag,address:this.address,khzt:this.khzt,lng:this.longitude,lat:this.latitude}
      console.log(param)
      debugger
      addCustomer(param).then(response =>{
        debugger
        if (response.code === 200) {
          if(response.data.code == 1){
            Dialog.alert({
              title: '',
              message: '提交成功'
            }).then(() => {
              // on close
              this.$router.go(-1) // 返回上一层
            })
          }

          if(response.data.code == 0 ){
            Toast.fail(response.data.msg)
          }

        } else {

          Toast.fail(response.msg)
        }
      })

    },

    doback(){
      this.$router.go(-1) // 返回上一层
    },

    showKhjb(){
      this.jbShow = true
    },

    showKhzt(){
      this.khztShow = true
    },

    onSelectKhjb(item){
      this.khjbname = item.name
      this.khjb = item.id
      this.jbShow = false
    },

    onSelectKhzt(item){
      this.khztname = item.name
      this.khzt = item.id
      this.khztShow = false
    }

  }
}
</script>
<style lang="scss" scoped>

.container{
  width: 100%;
  height: calc(100vh);
  background-color: white;
}

.navclass{
  background-color:#f8f8f8;
}

.btn{
  padding-left: 20px;
  padding-right: 20px;
  padding-top: 30px;
  background-color: white;
  padding-bottom: 150px;
}

#allmap{
  height:200px;
}

.amap-demo {
  height: 200px;
}

</style>
